import { AdminUsers } from '@libs/db/models/user.model';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { IPaginationFormWithCondition } from 'types/requestParams';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class UserService {
  constructor(
    @InjectModel('AdminUsers') private readonly userModel: Model<AdminUsers>,
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
  ) { }
  async createUser(body) {
    try {
      const doc = await this.userModel.create(body);
      await doc.save();
      return doc;
    } catch (e) {
      return new HttpException('后台错误', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * @breif: 查询用户列表,可待条件，多条件查询
   * @param {IPaginationFormWithCondition} body
   * @return {*}
   */
  async findAll(body: IPaginationFormWithCondition) {
    try {
      const condition = [
        {
          $match: {
            // 多条件
            $and: [{ username: { $regex: body.username ?? '' } }],
          },
        },
        {
          $facet: {
            total: [{ $count: 'count' }],
            rows: [
              { $skip: (body.pageNum - 1) * body.pageSize },
              { $limit: body.pageSize },
            ],
          },
        },
        {
          $project: {
            list: '$rows',
            total: { $arrayElemAt: ['$total.count', 0] },
          },
        },
      ];
      const result = await this.userModel.aggregate(condition);
      return result[0];
    } catch (e) {
      return new HttpException('后台错s误', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 获取用户信息
   * @param id (用户id)
   * @returns 
   */
  async getUserInfo(req) {
    try {
      let token = req.headers.authorization.split('Bearer ')[1];
      const tokenInfo = this.jwtService.verify(token, {
        secret: this.configService.get<string>('SECRET_KEY')
      })
      const userInfo = await this.userModel.findById(tokenInfo._id);
      return userInfo
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  async update(body: any) {
    try {
      await this.userModel.findByIdAndUpdate(body._id, body);
      return 'update success';
    } catch (e) {
      return new HttpException('后台错误', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * @breif: 删除角色
   * @param {string} id
   * @return {*}
   */
  async remove(id: string | number) {
    try {
      await this.userModel.findByIdAndDelete(id);
      return 'ok';
    } catch (e) {
      return new HttpException('后台错误', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
